package folder.main.exp2.algorithms;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import folder.model.network.Network;
import folder.model.node.Node;
import folder.model.virtual.VirtualNetwork;

public class KCenter extends Algorithm2
{
	// Algorithm
	
	public static KCenter kCenter( Network network, double delayThreshold, List< VirtualNetwork > virtualNetworks )
	{
		return new KCenter( network, delayThreshold, virtualNetworks );
	}
	
	public KCenter( Network network, double delayThreshold, List<VirtualNetwork> virtualNetworks )
	{
		super( network, delayThreshold, virtualNetworks );
		
		this.setValues( network );
		this.comparator = new ComparatorKCenter();
		this.checkAlgorithm = this.run();
	}
	
	private void setValues( Network network )
	{
		List< Node > bag = new ArrayList< Node >();
		
		for(  Node node: network.getNodes() )
			bag.add( node );
		
		int min = 0;
		int max = 19;
		int intRandom = (int) Math.floor( Math.random() * ( max - min + 1 ) + min );
		Node nodeNext = null;
		
		for( Node node: bag )
			if( node.getIdentifier() == intRandom )
				nodeNext = node;
		
		int i = 0;
		nodeNext.setIdentifierRandom( i++ );
		bag.remove( nodeNext );
		
		while( bag.size() > 0 )
		{
			nodeNext = getNodeDelayLongest( nodeNext, bag );
			nodeNext.setIdentifierRandom( i++ );
			bag.remove( nodeNext );
		}
	}
	
	private Node getNodeDelayLongest( Node nodeSource, List< Node > bag )
	{
		double delay = 0;
		Node nodeNext = null;
		
		for( Node nodeBag: bag )
			if( nodeSource.getDelayToNodeTarget( nodeBag ) > delay )
			{
				delay = nodeSource.getDelayToNodeTarget( nodeBag );
				nodeNext = nodeBag;
			}
	
		return nodeNext;
	}
	
	// Comparator
	
    private class ComparatorKCenter implements Comparator< Node >
    {
    	@Override
    	public int compare( Node nodeX, Node nodeY )
    	{
    		Double identifierRandomNodeX = nodeX.getIdentifierRandom();
    		Double identifierRandomNodeY = nodeY.getIdentifierRandom();
    		
    		return identifierRandomNodeX.compareTo( identifierRandomNodeY );
    	}
    }

}
